const express = require('express');
const router = express.Router();
const query = require('../config/db');
const md5 = require('md5');
const jwt = require("jsonwebtoken");

// 轮播图
router.get('/banner', async (req, res, next) => {
    let sql = `select * from e_banners where isshow=1`;
    let result = await query(sql);
    res.send({
        success: true,
        msg: '查询成功',
        status: 200,
        data: result
    });
})

// 首页课程
router.get('/course', async (req, res, next) => {
    let sql = `select * from e_course where type='${req.query.type}'`;
    let result = await query(sql);
    res.send({
        success: true,
        msg: '查询成功',
        status: 200,
        data: result
    });
})

// 注册
router.post('/register', async (req, res, next) => {
    // 从前端获取参数
    let { username, password, createdate } = req.body;
    // // 判断之前是否已经注册过
    let sql2 = `select * from e_member where username='${username}'`;
    let result2 = await query(sql2);
    if (result2.length > 0) {
        next('该用户已注册');
        return;
    }

    // 密码加密
    password = md5(md5(password).substr(4, 6));

    // 注册
    let mid = new Date().getTime() + (Math.random() + '').substr(3, 6);
    let sql = `insert into e_member (mid,username,password,sex,createdate) values ('${mid}','${username}','${password}','1','${createdate}')`;
    let result = await query(sql);
    if (result.affectedRows > 0) {
        res.send({
            success: true,
            msg: '注册成功',
            status: 200
        })
    } else {
        next('注册失败')
    }
});

// 登录
router.post('/login', async (req, res, next) => {
    // 从前端获取到的参数
    let { username, password } = req.body;
    let sql = `select * from e_member where username='${username}'`;
    let result = await query(sql);

    if (result.length == 0) {
        next('该用户不存在');
        return;
    }
    // 存在, 取出数据
    let obj = result[0];
    // 密码加密
    password = md5(md5(password).substr(4, 6));
    if (obj.password == password) {
        // 生成一个token
        // 要加密的数据
        let data = {
            mid: obj.password,
            username: obj.username
        }
        // 密匙
        let sectet = '加一个密匙，不让你知道！！！';
        let token = jwt.sign(data, sectet, { expiresIn: 10 * 60 });
        // 将obj中的密码删除
        delete obj.password;
        // 登录成功
        res.send({
            success: true,
            msg: '登录成功',
            status: 200,
            data: {
                ...obj,
                token
            }
        })
    } else {
        next('用户密码错误');
    }
})

module.exports = router;
